<?php
class ResourcePagesController extends AppController {
	public $name = 'ResourcePages';
	public $uses=array('ResourcePage','ResourceCategory','Resource','ResourceDetail');

	function admin_index(){
		//get filter field
		$filterField=array(
		//$this->uses[0].'.serie'=>_resource('serie',true)
		);
		//su dung khi site co chuc nang da ngon ngu==========================
		//set list cac country name ra view		
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		//===================================================================
		$this->set('data1',$this->admin_getList());
		$this->set('filterField',$filterField);
		$this->render('admin_index','ajax');
	}

	function admin_lists(){
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check($this->uses[0])){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>'',
				'fields'=>null,
				'order'=>$this->uses[0].'.created desc',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);
		}



		//su dung khi site co chuc nang da ngon ngu==========================
		//khai bao ngon ngu cua model, khi lay data, thi model nay se lay cac data theo ngon ngu da duoc chon
		//$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		//===================================================================

		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ...
		$this->paginate=$this->Session->read($this->uses[0]);
		//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
		//lay data da duoc phan trang va truyen vao bien $data0
		$data0=$this->paginate($this->uses[0]);

		
		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);

		
		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website.
		$this->render('admin_lists','ajax');
	}
	
	function admin_translate($cid=null,$locale=null){
		//su dung khi site co chuc nang da ngon ngu==========================
		//neu khong truyen vao ngon ngu thi ngon ngu mac dinh cua data duoc them vao se la ngon ngu duoc doc tu session
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		//khai bao ngon ngu cua model, khi do, ngon ngu cua data duoc luu vao database la $locale
		$this->{$this->uses[0]}->locale=array($locale);
		//====================================================================
		$isInsert=false;
		if(intval($cid)>0){			
			if(!empty($this->data)){
				if(isset($this->data[$this->uses[0]]) && count($this->data[$this->uses[0]])>0){
					foreach($this->data[$this->uses[0]] as $k=>$v){
						$v['id']=$k;
						$this->{$this->uses[0]}->save($v);
					}
					$isInsert=true;
					$this->Session->write('message',_resource('update data successful',true));
				}
			}
			else{
				$this->{$this->uses[0]}->recursive=-1;
				$this->data=$this->{$this->uses[0]}->find('all',array('conditions'=>array($this->uses[0].'.'.$this->{$this->uses[0]}->belongsTo[$this->uses[1]]['foreignKey']=>$cid)));
		
			}
		}

		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		$this->set('cid',$cid);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('isInsert',$isInsert);
	}

	function admin_add($locale=null){
		//su dung khi site co chuc nang da ngon ngu==========================
		//neu khong truyen vao ngon ngu thi ngon ngu mac dinh cua data duoc them vao se la ngon ngu duoc doc tu session
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		//khai bao ngon ngu cua model, khi do, ngon ngu cua data duoc luu vao database la $locale
		$this->{$this->uses[0]}->locale=$locale;
		//====================================================================
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		$isInsert=false;
		if(!empty($this->data)){
			$data=$this->data;
			$data[$this->uses[0]][$this->{$this->uses[0]}->belongsTo[$this->uses[1]]['foreignKey']]=$this->Session->read($this->uses[0].'.catid');
			if($this->{$this->uses[0]}->create($data) && $this->{$this->uses[0]}->validates()){
								
				if($this->{$this->uses[0]}->save($data)) {
					$this->data=null;
					$isInsert=true;
					$this->Session->write('message',_resource('insert data successful',true));
				} else {
					$this->Session->write('error',_resource('can not insert data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}

		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('isInsert',$isInsert);
	}

	function admin_edit($id=null,$locale=null){
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		$this->{$this->uses[0]}->locale=$locale;
		$isInsert=false;

		if(!empty($this->data)){			
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
										
				if($this->{$this->uses[0]}->save($this->data)) {
					
						
					$this->data=null;					
					$isInsert=true;
					$this->Session->write('message',_resource('update data successful',true));

				} else {
					$this->Session->write('error',_resource('can not update data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
		//get data from default language
				if($this->{$this->uses[0]}->locale!=$this->Session->read('adminLang') && $this->webConfig['is_multi_lang']){
					$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
					$this->data =$this->{$this->uses[0]}->read(null,$id);
					$this->{$this->uses[0]}->locale=$locale;
					$data =$this->{$this->uses[0]}->read(null,$id);
					//get data of current select language
					foreach($this->{$this->uses[0]}->actsAs['Translate'] as $k=>$v){						
						$this->data[$this->uses[0]]['default'.$v]=$this->data[$this->uses[0]][$v];
						$this->data[$this->uses[0]][$v]=$data[$this->uses[0]][$v];
					}					
				}
				else{
					$this->data =$this->{$this->uses[0]}->read(null,$id);
				}
				
				if(empty($this->data)){	
					$this->Session->write('error',_resource('data not found',true));				
					$this->render('admin_editNotFound');
				}
		}



		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('data1',$this->admin_getList());
		$this->set('isInsert',$isInsert);
	}
	function admin_delete_resource($id=null){		
		$this->layout=null;
		$this->{$this->uses[2]}->delete($id);
		$this->{$this->uses[3]}->deleteAll('resource_id='.$id);
		
	}
	function admin_resource($id=null,$locale=null){
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		$this->{$this->uses[0]}->locale=$locale;
		$isInsert=false;
		$rdata=$this->{$this->uses[0]}->read(null,$id);
		if($rdata){
			if(!empty($this->data)){	
				//t($this->data);
				//save		
				if(count($this->data[ResourceDetail])>0){
					foreach($this->data[ResourceDetail] as $k=>$v){	
						if($k<0)$k=null;					
						$this->ResourceDetail->save(array('ResourceDetail'=>array('message'=>$v['message'],'id'=>$k,'locale'=>$locale,'resource_id'=>$v['resource_id'])));
						
					}					
					
				}
				//create
				if(count($this->data[ResourceNew])>0){
					$resourcedata=array();
					$lsname=array();
					$lsmessage=array();
					$resourcedetaildata=array();
					
					foreach($this->data[ResourceNew] as $k=>$v){
						if(!empty($v['name'])){
							$resourcedata[]=array('Resource'=>array('name'=>$v['name'],'resource_page_id'=>$id));
							//$this->{$this->uses[2]}->save(array('Resource'=>array('name'=>$v['name'])));							
							$lsname[]=$v['name'];	
							$lsmessage[$v['name']]=$v['message'];					
						}						
					}
					$this->{$this->uses[2]}->saveMany($resourcedata);
					//get resourc id					
					$lsid=$this->{$this->uses[2]}->find('list',array('conditions'=>array('name'=>$lsname),'fields'=>array('name','id')));
					//save resource detail
					foreach($lsmessage as $k=>$v){
						$resourcedetaildata[]=array('ResourceDetail'=>array('message'=>$v,'resource_id'=>$lsid[$k],'locale'=>$locale));
					}
					$this->{$this->uses[3]}->saveMany($resourcedetaildata);
				}
				$isInsert=true;
				$this->Session->write('message',_resource('update data successful',true));
			}else{
			//get data from resource table
					$options['joins'] = array(
					    array('table' => 'resource_details',
					        'alias' => $this->uses[3],
					        'type' => 'left',
					        'conditions' => array(
					            $this->uses[2].'.id = '.$this->uses[3].'.resource_id',
					            $this->uses[3].'.locale'=>$locale
					        )
					    )
					);
					$options['conditions']=array(
						$this->uses[2].'.'.$this->{$this->uses[2]}->belongsTo[$this->uses[0]]['foreignKey']=>$id
					);	
					$options['fields']=array('
					`ResourceDetail`.`message`,
					`ResourceDetail`.`id`,
					`Resource`.`name`,
					`Resource`.`id`
					');		
					$options['order']=array('`Resource`.`id` asc');
				$data=$this->{$this->uses[2]}->find('all',$options);
				$this->set('data',$data);
					//t($data);
			}
			$this->set('page',$rdata[$this->uses[0]]['name']);
		}
		else{
			$this->Session->write('error',_resource('data not found',true));				
			$this->render('admin_editNotFound');
		}



		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		$this->set('id',$id);
		if($this->webConfig['is_multi_lang'])
			$this->set('listLang',$this->Common->listCountry());
		$this->set('isInsert',$isInsert);
	}

	function admin_delete($id = null) {
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->query('delete from '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' where id in ('.implode(',',array_keys($id_arr)).')' );			
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();	
	}

	function admin_published($id=null,$value=1,$field=0){
	$id_arr=null;
		$all=false;		
		switch($field){
			case 1: $fieldname='best';break;
			case 2: $fieldname='bestbuy';break;
			default: $fieldname='published';
		}
		if((!intval($value) && $value!=0) || intval($value)>1){
			$value=1;
		}
		
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
			$all=true;
		} 
		
		//if url
		if(intval($id) && !$all){
			$id_arr[$id]='';
		}
		
		if(count($id_arr)>0){			
			$this->{$this->uses[0]}->query('update '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' set '.$fieldname.'='.$value.' where id in ('.implode(',',array_keys($id_arr)).')' );
		}
		if (!$all) {			
			$this->set('value',$value);
			$this->set('field',$field);
			$this->set('fieldname',$fieldname);
			$this->set('id',intval($id));
			$this->render('admin_published','ajax');		
		} else {
			$this->admin_lists();
		}

	}

	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}

	function admin_page($page=1){
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists();
	}

	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists();
	}

	function admin_filter(){
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists();
	}
	/*
	 * ham dung de save thu tu cua tung mau tin
	 */
	function admin_save(){
		if(isset($this->params['form']['order'])){
			foreach($this->params['form']['order'] as $k=>$v){
				if(intval($v)){
					//set view order for category
					$this->{$this->uses[0]}->updateAll(array($this->uses[0].'.view_order'=>intval($v)),array($this->uses[0].'.id'=>$k));
				}
			}
		}
		$this->Session->write('message',_resource('view order has been update',true));
		$this->admin_lists();
	}

	/*
	 * ham dung khi co su dung chuc nang da ngon ngu
	 * dung de change locale cua he thong
	 * tham so truyen vao la locale cua ngon ngu
	 */
	function admin_changeLocale($locale=null){
		//luu session
		if($locale){
			$this->Session->write('adminLang',$locale);
		}
		//reload lai luoi de apply locale vua change
		$this->admin_lists();
	}


	
	function admin_getList($locale=null){
		$rt=array();
		$this->{$this->uses[1]}->locale=$this->Session->read('adminLang');
		$data=$this->{$this->uses[1]}->find('all');
		foreach($data as $k=>$v){
			$rt[$v[$this->uses[1]]['id']]=$v[$this->uses[1]]['name'];
		}
		return $rt;
		
	}

	
	function admin_selCat($id=null,$newpage=1) {
		//kiem tra neu submit tu form
		//luu dieu kien chon
		$conditions=null;
		$conditions=$this->Session->read($this->uses[0].'.conditions');
		$conditions[$this->uses[0].'.'.$this->{$this->uses[0]}->belongsTo[$this->uses[1]]['foreignKey']]=intval($id);
		if($id!=null){
			//luu sesssion de giu lai gia da chon
			$this->Session->write($this->uses[0].'.catid',intval($id));
		}
		else{
			$this->Session->write($this->uses[0].'.catid','');
			unset($conditions[$this->uses[0].'.'.$this->{$this->uses[0]}->belongsTo[$this->uses[1]]['foreignKey']]);
		}
		$this->Session->write($this->uses[0].'.conditions',$conditions);
		if($newpage)$this->admin_index();
		else $this->admin_lists();
	}

}
?>
